package lumis.service.portalmanagement.clock;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.Source;
import lumis.portal.PortalException;
import lumis.portal.clock.ClockConfig;
import lumis.portal.clock.IClockManager;
import lumis.portal.manager.ManagerFactory;
import lumis.util.XmlUtil;

/**
 * Process Action handler to handle Portal Clock Actions.
 *
 * @version $Revision: 10825 $ $Date: 2009-08-04 12:36:40 -0300 (Tue, 04 Aug 2009) $
 * @since 5.0.0
 */
@SuppressWarnings("unchecked")
public class ClockProcessActionHandler extends ProcessActionHandler<Source>
{
	public void processAction() throws PortalException
	{
		String actionType = XmlUtil.readAttributeString("actionType", processActionNode);
		
		if (actionType != null)
		{
			if (actionType.equals("lum_EventEnable"))
			{
				//enable
				setClockEnabledState(true);
			}
				
			else if (actionType.equals("lum_EventDisable"))
			{
				//disable
				setClockEnabledState(false);
			}
			else if (actionType.equals("lum_EventWaiting"))
			{
				//reset
				ResetClockState();
			}
		}
	}
	
	/**
	 * Reset the Clock State.
	 * 
	 * @throws PortalException
	 * @since 5.0.0
	 */
	public void ResetClockState() throws PortalException
	{
		String[] clockIds = (String[])getParameter("id");
		IClockManager clockManager = ManagerFactory.getClockManager();
		
		if(clockIds != null && clockIds.length > 0)
		{
			for (String clockId: clockIds)
				clockManager.setRunning(sessionConfig, clockId, false, transaction);
		}
		else
			throw new PortalException("STR_NO_ITEM_SELECTED", getResource());

		addDefaultResponse();
	}
	
	/**
	 * Sets the given @param as the Clock state.
	 * @param enabled the boolean clock state
	 * @throws PortalException
	 * @since 5.0.0
	 */
	private void setClockEnabledState(boolean enabled) throws PortalException
	{
		String[] clockIds = (String[])getParameter("id");
		IClockManager clockManager = ManagerFactory.getClockManager();
		
		if(clockIds != null && clockIds.length > 0)
		{
			for (String clockId: clockIds)
			{
				if(enabled)
					clockManager.enable(sessionConfig, clockId, transaction);
				else
					clockManager.disable(sessionConfig, clockId, transaction);
			}
		}
		else
			throw new PortalException("STR_NO_ITEM_SELECTED", getResource());

		addDefaultResponse();
	}
		
}
